/*
 * @Date: 2020-02-19 18:03:25
 * @名称: 阅读漫画页面 - 内容 - 控制器
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2020-08-23 00:17:06
 * @FilePath: /bica_acg/lib/Pages/ReadingComics/Widget/ReadingComicsBody/ReadingComicsBodyController.dart
 */
import 'dart:async';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pica_acg/GlobalFunction.dart';
import 'package:pica_acg/GlobalSettings.dart';
import 'package:pica_acg/GlobalVarlable.dart';
import 'package:pica_acg/GlobalWidget.dart';
import 'package:pica_acg/LanguAge/LanguAgeController.dart';
import 'package:pica_acg/Pages/ReadingComics/Widget/ReadingComicsBox/ReadingComicsBoxController.dart';
import 'package:pica_acg/tools/NetWorkController.dart';
import 'package:pica_acg/tools/extends/Json/ComicsInfo/ComicsInfoListJson.dart';
import 'package:yin_drag_sacle/yin_drag_sacle.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

var globalKeyReadingComicsReadingComicsBodyControllerState =
    new GlobalKey<ReadingComicsReadingComicsBodyControllerState>(); //引入 下载页面列表

class ReadingComicsReadingComicsBodyController extends StatefulWidget {
  ReadingComicsReadingComicsBodyController({
    Key key,
    this.allPage,
    this.comicsinfoEpisodesList,
    this.parentWindowID,
    this.comicsId,
    this.subsectionId,
    this.bookDownloadChapterImagesList,
    this.localData = false,
  }) : super(key: key);
  List bookDownloadChapterImagesList;
  ComicsInfoListJson comicsinfoEpisodesList;
  int allPage;
  final String comicsId;
  final String subsectionId;
  final parentWindowID;
  bool localData;
  @override
  ReadingComicsReadingComicsBodyControllerState createState() =>
      ReadingComicsReadingComicsBodyControllerState();
}

double topDistance = 0.0;
double leftDistance = 0.0;
Axis $pageTurningMode = (setting.pageTurningMode == 0)
    ? Axis.vertical
    : Axis.horizontal; // 观看模式 横向查看 还是竖向
// Axis $pageTurningMode = Axis.horizontal; // 观看模式 横向查看 还是竖向
int whatPageDoYouSee;
Timer timer;

class ReadingComicsReadingComicsBodyControllerState
    extends State<ReadingComicsReadingComicsBodyController> {
  CarouselSlider basicSlider;
  @override
  void initState() {
    super.initState();
    whatPageDoYouSee = 1;
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> list = List(); //这是列表要被显示

    if (widget.comicsinfoEpisodesList.data.pages.docs.length != 0) {
      // print('我是加载的网络漫画');
      list = List.generate(
        widget.comicsinfoEpisodesList.data.pages.docs.length,
        (index) {
          /* print(widget.comicsinfoEpisodesList.data.pages.docs[index].media
                .fileServer +
            '/static/' +
            widget.comicsinfoEpisodesList.data.pages.docs[index].media.path); */
          return DragScaleContainer(
            child: NetworkSuperImage(
              url: imagesIsPath(
                  widget.comicsinfoEpisodesList.data.pages.docs[index]),
            ),
            doubleTapStillScale: $global_ReadingComicsZoomIn,
            maxScale: $global_ReadingComicsMagnification, //放大最大倍数
          );
        },
      );
    } else if (widget.bookDownloadChapterImagesList != null &&
        widget.bookDownloadChapterImagesList.length > 0) {
      // print('我是加载的本地漫画');
      list = List.generate(
        widget.bookDownloadChapterImagesList.length,
        (index) {
          //在这里判断漫画是否下载完毕 没下载完毕从网络获取
          /* var imagesWidget = DragScaleContainer(
            child: Image.file(
              file,
              frameBuilder: (BuildContext context, Widget child, int frame,
                  bool wasSynchronouslyLoaded) {
                print(wasSynchronouslyLoaded);
                if (wasSynchronouslyLoaded) {
                  return child;
                }
                return DragScaleContainer(
                  child: NetworkSuperImage(
                    url: springboard() +
                        widget.bookDownloadChapterImagesList[index]
                            ["SeverAddress"] +
                        widget.bookDownloadChapterImagesList[index]
                            ["ImagesName"],
                  ),
                  doubleTapStillScale: $global_ReadingComicsZoomIn,
                  maxScale: $global_ReadingComicsMagnification, //放大最大倍数
                );
              },
            ), */

          var imagesWidget = DragScaleContainer(
            child: LocalCustomImage(
              src:
                  "/Cartoon/${widget.comicsId}/${widget.bookDownloadChapterImagesList[index]["ChapterId"]}/${widget.bookDownloadChapterImagesList[index]["PictureAliases"]}",
            ),
            doubleTapStillScale: $global_ReadingComicsZoomIn,
            maxScale: $global_ReadingComicsMagnification, //放大最大倍数
          );
          return imagesWidget;

          /* file.exists().then((value) async {
            if (!value) {
              imagesWidget = 
            }
          }); */

          /* return DragScaleContainer(
            child: Image.file(
              file,
            ),
            doubleTapStillScale: $global_ReadingComicsZoomIn,
            maxScale: $global_ReadingComicsMagnification, //放大最大倍数
          ); */
        },
      );
    } else {
      print('发生意外错误ReadingComicsBodyController');
    }
    Widget pageEnd = Container(
      child: Stack(
        children: <Widget>[
          Image.network(
            'https://i0.hdslb.com/bfs/album/f873cbd88d5db57390a228c13d490657fd72bd81.jpg',
          ),
          Text('正在获取下一个章节'),
        ],
      ),
      alignment: Alignment.center,
    );
    if (!widget.localData) {
      list.add(pageEnd);
    }
    readOver() {
      //阅读完毕
      aotuPlay(false);
      Navigator.of(context).push(
        PageRouteBuilder(
          pageBuilder: (context, _, __) => GlobalTipsExtend(
            body: 'a',
            height: 700,
            logo: {
              "isLogo": true,
              "logoSrc": 'images/Tisp/Success.png',
            },
            expand: true,
            expButton: {
              "isExpButton": true,
              "expButtonSuccessName":
                  languAre().$languAgeReadingComicsReadingComicsBodyController[
                      "readOver"]["tips_expButtonSuccessName"],
              "expButtonSuccessOntab": () {
                Navigator.pop(context);
              },
              "expButtonErrorName":
                  languAre().$languAgeReadingComicsReadingComicsBodyController[
                      "readOver"]["tips_expButtonErrorName"],
              "expButtonErrorOntab": () {
                print('object1');
              },
            },
            expandBody: Container(
              margin: EdgeInsets.only(
                top: ScreenUtil().setHeight(519),
              ),
              height: ScreenUtil().setHeight(300),
              alignment: Alignment.topCenter,
              child: ClipRRect(
                borderRadius: new BorderRadius.vertical(
                  top: Radius.elliptical(20, 20),
                ),
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      Container(
                        child: Text(
                          languAre()
                                  .$languAgeReadingComicsReadingComicsBodyController[
                              "readOver"]["tips_Title"],
                          style: TextStyle(
                            fontSize: 30.0,
                            fontWeight: FontWeight.w700,
                            color: Color(0xFFed97b7),
                            decoration: TextDecoration.none,
                          ),
                        ),
                        margin: EdgeInsets.only(
                          top: ScreenUtil().setHeight(5),
                        ),
                        alignment: Alignment.center,
                      ),
                      Container(
                        child: Text(
                          languAre()
                                  .$languAgeReadingComicsReadingComicsBodyController[
                              "readOver"]["tips_Subheading"],
                          style: TextStyle(
                            decoration: TextDecoration.none,
                            fontSize: 14.0,
                            color: Color.fromRGBO(79, 79, 79, 1),
                          ),
                        ),
                        margin: EdgeInsets.only(
                          top: ScreenUtil().setHeight(5),
                        ),
                        alignment: Alignment.center,
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          opaque: false,
        ),
      );
    }

    loadNextPage(nextPage) {
      //加载下一页 //! 当数据为网络的在进行加载
      NetWorkController.get(
        getComicsInfoEpisodes(
              widget.comicsId,
              widget.subsectionId,
            ) +
            '&page=${widget.comicsinfoEpisodesList.data.pages.page + 1}',
        (callBack) {
          ComicsInfoListJson temp = ComicsInfoListJson.fromJson(callBack);
          widget.comicsinfoEpisodesList.code = temp.code;
          widget.comicsinfoEpisodesList.message = temp.message;
          widget.comicsinfoEpisodesList.data.ep = temp.data.ep;
          widget.comicsinfoEpisodesList.data.pages.page = temp.data.pages.page;
          widget.comicsinfoEpisodesList.data.pages.pages =
              temp.data.pages.pages;
          widget.comicsinfoEpisodesList.data.pages.total =
              temp.data.pages.total;
          widget.comicsinfoEpisodesList.data.pages.limit =
              temp.data.pages.limit;
          widget.comicsinfoEpisodesList.data.pages.docs
              .addAll(temp.data.pages.docs);
          globalKeyReadingComicsReadingComicsBoxControllerState.currentState
              .setProgress(
            currentProgress: nextPage + 1,
            allProgress: widget.comicsinfoEpisodesList.data.pages.docs.length,
          );
          whatPageDoYouSee = nextPage + 1;
          // print(callBack);
          setState(() {});
        },
        headers: getApiRequestHeadrs("ComicsEpisodes"),
      );
    }

    basicSlider = CarouselSlider(
      scrollDirection: $pageTurningMode,
      height: ScreenUtil().setHeight(1344),
      aspectRatio: 20 / 9,
      viewportFraction: 1.0,
      initialPage: 0,
      enableInfiniteScroll: false,
      reverse: false,
      autoPlay: false,
      autoPlayInterval: Duration(seconds: 3),
      autoPlayCurve: Curves.fastOutSlowIn,
      pauseAutoPlayOnTouch: Duration(seconds: 10),
      enlargeCenterPage: false,
      onPageChanged: (e) {
        if (e == widget.comicsinfoEpisodesList.data.pages.docs.length &&
            !widget.localData) {
          print('到了最后一页了 重新获取下一集');
          if (widget.comicsinfoEpisodesList.data.pages.pages !=
              widget.comicsinfoEpisodesList.data.pages.page) {
            loadNextPage(e);
          } else {
            readOver();
          }
        } else {
          if (widget.localData == true) {
            //判断是不是本地资源
            whatPageDoYouSee = e + 1;
            try {
              //更新框架页面显示当前页数
              globalKeyReadingComicsReadingComicsBoxControllerState.currentState
                  .setProgress(currentProgress: whatPageDoYouSee);
            } catch (e) {
              print(
                  "发生意外错误 错误位置 globalKeyReadingComicsReadingComicsBoxControllerState 错误原因 $e");
            }
            if (whatPageDoYouSee == widget.allPage) {
              //是本地资源 并且 是全部页面了
              print('阅读完毕');
              print(whatPageDoYouSee);
              print(widget.allPage);
              print('阅读完毕');
              readOver();
            }
          } else {
            //不是本地的
            whatPageDoYouSee = e + 1;
            try {
              //更新框架页面显示当前页数
              globalKeyReadingComicsReadingComicsBoxControllerState.currentState
                  .setProgress(currentProgress: whatPageDoYouSee);
            } catch (e) {
              print(
                  "发生意外错误 错误位置 globalKeyReadingComicsReadingComicsBoxControllerState 错误原因 $e");
            }
          }
        }
      },
      items: list,
    );

    /* basicSlider = CarouselSlider.builder(
      itemCount: widget.allPage,
      height: ScreenUtil().setHeight(1344),
      aspectRatio: 20 / 9,
      viewportFraction: 1.0,
      initialPage: 0,
      enableInfiniteScroll: false,
      reverse: false,
      autoPlay: false,
      autoPlayInterval: Duration(seconds: 3),
      autoPlayAnimationDuration: Duration(milliseconds: 800),
      autoPlayCurve: Curves.fastOutSlowIn,
      pauseAutoPlayOnTouch: Duration(seconds: 10),
      enlargeCenterPage: false,
      onPageChanged: (e) {
        globalKeyReadingComicsReadingComicsBoxControllerState.currentState
            .setProgress(currentProgress: e + 1);
      },
      scrollDirection: Axis.horizontal,
      itemBuilder: (BuildContext context, int itemIndex) => Container(
        child: DragScaleContainer(
          child: Image.network(widget.comicsinfoEpisodesList.data.pages
                  .docs[itemIndex].media.fileServer +
              '/static/' +
              widget.comicsinfoEpisodesList.data.pages.docs[itemIndex].media
                  .originalName),
          doubleTapStillScale: false,
          maxScale: 4, //放大最大倍数
        ),
      ),
    ); */
    return Container(
      child: basicSlider,
    );

    return Swiper(
      onIndexChanged: (e) {
        globalKeyReadingComicsReadingComicsBoxControllerState.currentState
            .setProgress(currentProgress: e + 1);
      },

      loop: false,
      itemCount: widget.allPage,
      autoplay: false,
      //是否自动播放
      autoplayDelay: 3000,
      //自动播放延迟
      autoplayDisableOnInteraction: true,
      //触发时是否停止播放
      duration: 600,
      //动画时间
      pagination: new SwiperPagination(
        alignment: Alignment.bottomRight,
        builder: new DotSwiperPaginationBuilder(
            size: 8,
            activeSize: 12,
            color: Color.fromARGB(30, 255, 255, 255),
            activeColor: Color.fromARGB(255, 255, 255, 255)),
      ), //默认指示器
      //item数量
      itemBuilder: (BuildContext context, int index) {
        //item构建
        return new Stack(
          children: <Widget>[
            Container(
              alignment: Alignment.center,
              // child: Image.network(
              //   widget.data.data.banners[index].thumb.fileServer,
              // ),
              child: Container(
                child: Image.network(
                    'https://i0.hdslb.com/bfs/album/4fd2594d3da5c47b6dd45c146c38efa8f14047db.jpg'),
              ),
            ),
          ],
        );
      },
    );
    return Container(
      alignment: Alignment.center,
      width: ScreenUtil().setWidth(790),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(50)),
      child: GestureDetector(
        child: Container(
          child: PageView(
            scrollDirection: $pageTurningMode,
            //翻页模式 有 Axis.vertical 纵向 和 Axis.horizontal 横向
            children: <Widget>[
              DragScaleContainer(
                child: Image.network(
                    'https://i0.hdslb.com/bfs/album/4fd2594d3da5c47b6dd45c146c38efa8f14047db.jpg'),
                doubleTapStillScale: false,
                maxScale: 4, //放大最大倍数
              ),
              DragScaleContainer(
                child: Image.network(
                    'https://i0.hdslb.com/bfs/album/4fd2594d3da5c47b6dd45c146c38efa8f14047db.jpg'),
                doubleTapStillScale: false,
                maxScale: 4, //放大最大倍数
              ),
              DragScaleContainer(
                child: Image.network(
                    'https://i0.hdslb.com/bfs/album/4fd2594d3da5c47b6dd45c146c38efa8f14047db.jpg'),
                doubleTapStillScale: false,
                maxScale: 4, //放大最大倍数
              ),
              DragScaleContainer(
                child: Image.network(
                    'https://i0.hdslb.com/bfs/album/4fd2594d3da5c47b6dd45c146c38efa8f14047db.jpg'),
                doubleTapStillScale: false,
                maxScale: 4, //放大最大倍数
              ),
              DragScaleContainer(
                child: Image.network(
                    'https://i0.hdslb.com/bfs/album/4fd2594d3da5c47b6dd45c146c38efa8f14047db.jpg'),
                doubleTapStillScale: false,
                maxScale: 4, //放大最大倍数
              ),
            ],
          ),
        ),
      ),

      /* NetworkSuperImage(
          url:
              'http://picaapi.picacomic.com/comics/5cdd7aca176cc27873257bff/order/5d8b89c14c3b1e0211b2e860/pages?page=1',
        ),
        onTap: () {
          print('object');
        },
      ), */
    );
  }

  pageTurningMode(Axis scrollDirection) {
    //设置页面方向
    $pageTurningMode = scrollDirection;
    setState(() {});
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
  }

  toPage(int page) {
    basicSlider.jumpToPage(page - 1);
  }

  aotuPlay(bool state) {
    if (state) {
      timer = new Timer.periodic(
        new Duration(seconds: 1),
        (timer) {
          toPage(currentPageNumber++);
        },
      );
    } else {
      if (timer != null) {
        timer.cancel();
      }
    }
    setState(() {});
  }
}
